"""
计算期货与期货之间的基差，
步骤1、先提取主力合约的种类比如螺纹钢[01,05,10]
步骤2、计算不同的合约历史行情序列[01序列，05序列，10序列]
步骤3、计算期货与期货价差，根据排列组合有[螺纹01-螺纹05，……]6个
步骤4、上传到Mongodb

"""
import os
import sys
import pandas as pd
from itertools import permutations
from tools.utils import load_config
from tools.utils import get_chinese_name_to_ts_code
from tools.utils import get_ts_code_to_chinese_name
from tools.utils import first_dir_exists
from tools.utils import concat_and_build_dir
from tools.utils import check_str
from cal.cal_fut import generate_main_contract_time_series


def cal_fut_fut_basis(df1: pd.DataFrame, df2: pd.DataFrame, name: str):
    trade_date = sorted(list(set([t for t in df1.index if t in df2.index])))
    df1_loc = df1.copy().loc[trade_date]
    df2_loc = df2.copy().loc[trade_date]
    se = df1_loc.iloc[:, 0] - df2_loc.iloc[:, 0]
    se.name = name
    se_df = pd.DataFrame(se)
    se_df[1] = df1_loc['ts_code']
    se_df[2] = df2_loc['ts_code']
    se_df.index = [str(pd.to_datetime(str(s)))[:10] for s in se_df.index]
    return se_df


def cal_fut_fut_basis_by_ts_code(cfg, ts_code_lower, mode):
    chinese_name_map = get_ts_code_to_chinese_name(cfg)
    chinese_name = chinese_name_map[ts_code_lower]
    df_dic, _ = generate_main_contract_time_series(cfg, ts_code_lower, mode, only_close=False)
    fut_fut_basis_dic = {}
    name_dic = {}
    for c1, c2 in permutations(list(df_dic.keys()), 2):
        nme = f"{chinese_name}{c1}-{chinese_name}{c2}"
        v = cal_fut_fut_basis(df_dic[c1], df_dic[c2], nme)
        fut_fut_basis_dic[nme] = v
        name_dic[nme] = {'meiosis': f"{chinese_name}{c2}",
                         'minuend': f"{chinese_name}{c1}"}
    print(mode)
    return fut_fut_basis_dic, name_dic


if __name__ == "__main__":
    mode = "价差"
    path = first_dir_exists()
    cfg = load_config()
    cnttc = get_chinese_name_to_ts_code(cfg)
    for category, chinese_names in cfg['tjd_category'].items():
        category_path = concat_and_build_dir(path, category)
        for chinese_name in chinese_names:
            chinese_name_path = concat_and_build_dir(category_path, chinese_name)
            cd = cnttc[chinese_name]
            v = cal_fut_fut_basis_by_ts_code(cfg, cd, mode)
            for k, df in v.items():
                final_path = concat_and_build_dir(chinese_name_path, mode)
                save_path = f"{final_path}/{k}.xlsx"
                df.to_excel(check_str(save_path))
